var superAgent = require('superagent')
var appid = 'wxcd5d8b6f79d225ac';
var secret = '7c54d39723ea80f2718cabcc79171de5';
var baseUrl = 'https://api.weixin.qq.com'
var card = {
    lastGetTime: 0,
    expires_in: 0,
    access_token: '',
    getAccessToken(callback) {
        var _this = this;
        var timeNow = Date.now()
        restTime = Math.floor((this.expires_in * 1000 - (timeNow - this.lastGetTime)) / 1000)
        if (restTime > 0) {
            callback({
                access_token: this.access_token,
                expires_in: restTime
            })
            return
        }
        superAgent.get(baseUrl + '/cgi-bin/token')
            .query({
                grant_type: 'client_credential',
                appid,
                secret,
            })
            .end(function (err, response) {
                if (err) {
                    console.log(err)
                    return false
                }
                if (response.status === 200) {
                    var json = JSON.parse(response.text)
                    _this.lastGetTime = Date.now()
                    _this.expires_in = json.expires_in
                    _this.access_token = json.access_token
                    callback(json)
                }
            })
    },
    uploadImg(buffer, callback) {
        superAgent.post(baseUrl + '/cgi-bin/media/uploadimg')
            .query({
                access_token: this.access_token
            })
            .send({
                buffer
            })
            .end(function (err, response) {
                if (err) {
                    console.log(err)
                    return false
                }
                if (response.status === 200) {
                    console.log(response)
                    // var json = JSON.parse(response.text)
                    callback(response)
                }
            })
    },
    createCard(json, callback) {
        superAgent.post(baseUrl + '/card/create')
            .query({
                access_token: this.access_token
            })
            .send(json)
            .end(function (err, response) {
                if (err) {
                    console.log(err)
                    return false
                }
                if (response.status === 200) {
                    callback()
                }
            })
    }
}

module.exports = {
    card
}